package com.wyh.lotterysystem.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
public class RedisUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 存储数据
     */
    public boolean setRedis(String key, String value){
        try {
            stringRedisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e){
            log.error("验证码缓存失败，set({},{})：{}", key,value,e);
            return false;
        }
    }

    /**
     * 存储数据，并规定生命周期
     */
    public boolean setRedisAndTime(String key, String value, Long time){
        try {
            stringRedisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
            return true;
        }catch (Exception e) {
            log.error("验证码缓存失败，set({},{})：{}", key,value,e);
            return false;
        }
    }

    /**
     * 根据key获取value值
     */
    public String getValue(String key){
        try {
            return StringUtils.hasText(key) ?
                    stringRedisTemplate.opsForValue().get(key)
                    :null;
        } catch (Exception e) {
            log.error("验证码获取失败，set({})：{}", key,e);
            return null;
        }
    }

    /**
     * 根据key删除键值对
     */
    public boolean delRedis(String... key){
        try {
            if (key != null && key.length > 0){
                if (key.length == 1){
                    stringRedisTemplate.delete(key[0]);
                }else {
                    stringRedisTemplate.delete(
                            (List)CollectionUtils.arrayToList(key)
                    );
                }
            }
            return true;
        }catch (Exception e) {
            log.error("验证码删除失败，set({})：{}", key,e);
            return false;
        }
    }

    /**
     * 判断是否有对应的value
     */
    public boolean hasValueOfKey(String key){
        try {
            return StringUtils.hasText(key)?
                    stringRedisTemplate.hasKey(key)
                    :false;
        }catch (Exception e) {
            log.error("验证码查找失败，set({})：{}", key,e);
            return false;
        }
    }
}
